package com.ruoyi.common.utils.wxgzh;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.dto.AuthTokenException;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Created by admin on 2017/10/20.
 */
public class WeixinHelper {

    /**
     * 获取网页授权凭证
     *
     * @param appId     公众账号的唯一标识
     * @param appSecret 公众账号的密钥
     * @return getAccessToken
     */
    public static String getAccessToken(String appId, String appSecret) {
        String access_token = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?appid=APPID&secret=SECRET&grant_type=client_credential";
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        // 获取网页授权凭证
        JSONObject jsonObject = JSON.parseObject(HttpUtils.sendGet(requestUrl, ""));
        if (null != jsonObject) {
            try {
                access_token = jsonObject.getString("access_token");
            } catch (Exception e) {
                access_token = null;
//                int errorCode = jsonObject.getInteger("errcode");
//                String errorMsg = jsonObject.getString("errmsg");
            }
        }
        return access_token;
    }

    /**
     * 获取网页授权凭证
     *
     * @param appId     公众账号的唯一标识
     * @param appSecret 公众账号的密钥
     * @param code
     * @return WeixinAouth2Token
     */
    public static Wxoauth2token getOauth2AccessToken(String appId, String appSecret, String code) {
        Wxoauth2token wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        JSONObject jsonObject = JSON.parseObject(HttpUtils.sendGet(requestUrl, ""));
        System.out.println("{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}");
        System.out.println("获取网页凭证json数据的值是："+jsonObject.toString());
        if (null != jsonObject) {
            try {
                if (String.valueOf(jsonObject.get("errcode")).equals("40163")){
                    throw new AuthTokenException("短时间内请不要重复订阅",40163);
                }
                wat = new Wxoauth2token();
                wat.setAccessToken(jsonObject.getString("access_token"));

               // System.out.println("我将获取得到的access_token数据进行后台打出显示************************************");
                //System.out.println(jsonObject.getString("access_token"));

                //System.out.println("我将获取得到的openid数据进行后台打出显示************************************");
               // System.out.println(jsonObject.getString("openid"));

                wat.setExpiresIn(7200);
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));
                wat.setUpdateTime(new Date());
            } catch (Exception e) {
                wat = null;
                throw new AuthTokenException("短时间内请不要重复订阅",40163);
//                int errorCode = jsonObject.getInteger("errcode");
//                String errorMsg = jsonObject.getString("errmsg");
            }
        }
        return wat;
    }


    /**
     * 通过网页授权获取用户信息
     *
     * @param accessToken 网页授权接口调用凭证
     * @param openId      用户标识
     * @return SNSUserInfo
     */
    @SuppressWarnings({"deprecation", "unchecked"})
    public static JSONObject getSNSUserInfo(String accessToken, String openId) {
//        System.out.println("+++++++++++++++++++++++++++++++++accessToken:"+accessToken+"+++++++openId:"+openId+"+++++++++++++++++++++++++++");
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";
        requestUrl = String.format(requestUrl,accessToken,openId);
        System.out.println(requestUrl);
        // 通过网页授权获取用户信息
        JSONObject jsonObject = JSON.parseObject(HttpUtils.sendGet(requestUrl, ""));
        return jsonObject;
    }

    /**
     * @param touser
     * @param first
     * @param keyword1
     * @param keyword2
     * @param remark
     * @return
     */
    public static String parameterToJson(String touser, String first,
                                         String keyword1, String keyword2, String remark) {
        return String.format("{ \"touser\": \"%s\"," +
                        " \"template_id\": \"-i-f4_wtR0zYeJJdZkB6vdvkUn8GtXV3IaofR0rYVlI\", \"data\": {" +
                        " \"first\": { \"value\": \"%s\", \"color\": \"#173177\" }," +
                        " \"keyword1\": { \"value\": \"%s\", \"color\": \"#173177\" }," +
                        " \"keyword2\": { \"value\": \"%s\", \"color\": \"#173177\" }," +
                        " \"remark\": { \"value\": \"%s\", \"color\": \"#173177\" } } }",
                touser, first, keyword1, keyword2, remark);
    }

    /**
     * 微信JSSDK的ticket请求URL地址——jsapi_ticket
     * @param accessToken
     * @return
     * @throws Exception
     */
    public static String getTicket(String accessToken) throws Exception {
        String ticket =null;
        try {
            //获取票据的网址(由微信提供)
            JSONObject jsonObject = JSON.parseObject(HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi", ""));
            if (null != jsonObject) {
                try {
                    ticket = jsonObject.getString("ticket");
                    long expires_in = Long.valueOf(jsonObject.getString("expires_in"));
                    //TODO 设置过期时间
                } catch (Exception e) {
                    accessToken = null;
                    int errorCode = jsonObject.getInteger("errcode");
                    String errorMsg = jsonObject.getString("errmsg");
                    //log.error("获取ticket失败 errcode:{} errmsg:{}", jsonObject.getIntValue("errcode"), jsonObject.getString("errmsg"));
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ticket;
    }

    /**
     * 票据加密
     * @param jsapi_ticket
     * @param url
     * @return
     */
    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    public static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
    //获取UUID
    public static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }
    //获取时间戳
    public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
